package wiki.zimo.servlet.backstage;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import wiki.zimo.constant.Constant;
import wiki.zimo.dao.ProductDao;
import wiki.zimo.domain.Product;
import wiki.zimo.servlet.BaseServlet;
import wiki.zimo.utils.UUIDUtils;
import wiki.zimo.utils.UploadUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version v1.0
 * @auther: 子墨
 * @datetime: 2018/11/11 23:14
 * @description: 处理后台商品管理的servlet
 */
@WebServlet(value = "/productManage")
public class ProductManageServlet extends BaseServlet {

    ProductDao productDao = new ProductDao();

    /**
     * @auther: 子墨
     * @date: 2018/11/11 23:19
     * @describe: 商品添加或修改页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String editProductPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pid = request.getParameter("pid");
        Product product = productDao.findOneById(pid);

        request.setAttribute(Constant.PRODUCT, product);
        return Constant.URL_BACKSTAGE_PRODUCT_ADD;
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/13 16:29
     * @describe: 商品列表页
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String productListPage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Product> products = productDao.findAll();
        request.setAttribute(Constant.PRODUCTS, products);
        return Constant.URL_BACKSTAGE_PRODUCT_LIST;
    }


    /**
     * @auther: 子墨
     * @date: 2018/11/12 23:33
     * @describe: 新增或修改商品接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String updateProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> params = getParameterMap(request);

        String pid = (String) params.get("pid");
        Product product = new Product();

        if (pid == null || pid.equals("")) {
            // 新增
            BeanUtils.populate(product, params);
            product.setPid(UUIDUtils.getRandomId());
            product.setPdate(new Timestamp(System.currentTimeMillis()));

            productDao.insert(product);
            request.setAttribute(Constant.MSG, "新增商品“" + product.getPname() + "”成功");
        } else {
            // 修改
            product = productDao.findOneById(pid);
            BeanUtils.populate(product, params);
            product.setPdate(new Timestamp(System.currentTimeMillis()));

            productDao.update(product);
            request.setAttribute(Constant.MSG, "修改商品“" + product.getPname() + "”成功");
        }
        System.out.println(product);
        return productListPage(request, response);
    }

    /**
     * @auther: 子墨
     * @date: 2018/11/13 17:11
     * @describe: 删除商品信息接口
     * @param: [request, response]
     * @return: java.lang.String
     * @version v1.0
     */
    public String deleteProduct(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String pid = request.getParameter("pid");
        Product product = productDao.findOneById(pid);
        if (product != null) {
            productDao.delete(product);
            request.setAttribute(Constant.MSG, "删除商品“" + product.getPname() + "”成功");
            return productListPage(request, response);
        }
        return null;
    }


    /**
     * @auther: 子墨
     * @date: 2018/11/12 15:20
     * @describe: 将请求参数封装为一个map集合便于BeanUtils封装为对象
     * @param: [request]
     * @return: java.util.Map<java.lang.String, java.lang.Object>
     * @version v1.0
     */
    private Map<String, Object> getParameterMap(HttpServletRequest request) throws FileUploadException, IOException {
        Map<String, Object> map = new HashMap<>();

        // 使用fileupload
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List<FileItem> items = upload.parseRequest(request);
        for (FileItem item : items) {
            String key = item.getFieldName();
            if (item.isFormField()) {
                // 普通输入框
                String value = item.getString("utf-8");
                map.put(key, value);
            } else {
                // 文件输入框
                String fileName = item.getName();
                String realName = UploadUtils.getRealName(fileName);
                String randomName = UploadUtils.getRandomName(realName);
                String randomDir = UploadUtils.getRandomDir();

                InputStream input = item.getInputStream();

                String path = getServletContext().getRealPath(Constant.FILE_SAVE_PATH);
                File dir = new File(path, randomDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                FileOutputStream out = new FileOutputStream(new File(dir, randomName));
                IOUtils.copy(input, out);

                out.close();
                input.close();

                item.delete();

                map.put(key, Constant.FILE_SAVE_PATH + randomDir + randomName);
                System.out.println(Constant.FILE_SAVE_PATH + randomDir + randomName);
            }
        }
        System.out.println(map);
        return map;
    }
}
